/**
 *	Handles all dealings with the API
**/

var API = {
	
	_debug: false,
	_baseURL: "http://localhost:1337/",
	_reqs: { },
	
	//send your current move to the server
	sendMove: function(move) {
		this._doCall({
			type		:	"sendMove",
			move		:	move
		})
	},
	
	//get the latest move in your current game (gameId) from the server
	getMove: function(move, callback) {
		this._doCall({
			type		:	"getMove",
			move		:	move,
			callback	:	callback
		})
	},
	
	gamesList: function(callback) {
		this._doCall({
			type		:	"gamesList",
			callback	:	callback
		})
	},
	
	joinGame: function(move, callback) {
		this._doCall({
			type		:	"joinGame",
			move		:	move,
			callback	:	callback
		})
	},
	
	createGame: function(move, callback) {
		this._doCall({
			type		:	"createGame",
			move		:	move,
			callback	:	callback
		})
	},
	
	checkGameStatus: function(move, callback) {
		this._doCall({
			type		:	"checkGameStatus",
			move		:	move,
			callback	:	callback
		})		
	},
	
	//make the main calls
	_doCall: function(options) {
		var that = this,
			req = this._reqs[options.type] = new XMLHttpRequest()	//create and set up new XHR
		req.open("POST", this._baseURL, true)
		
		req.onreadystatechange = function() {
			if (req.readyState !== 4)  return
			
			if (req.status === 200) {
				if (that._debug) {
					console.log("client: " + options.type + " responded:")
					console.log(req.responseText)
				}
				if (typeof options.callback === "function") {
					options.callback(req.responseText)
				}
			} else {
				console.log("API." + options.type + " problem... error code: " + req.status)
				console.log(req.responseText)
			}
		}
		
		req.send(
			"?type=" + options.type + 								//type of req for server to parse
			"&payload=" + JSON.stringify(options.move)				//game details to send
		)
	},
	
	//kill all active XHRs
	kill: function() {
		for (var i in this._reqs) {
			this._reqs[i].abort()
		}
	}

}